﻿using Nancy.Json;
using Newtonsoft.Json;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Input;

namespace HotelManagementClient.Utlis
{
    public  class Encryptor
    {
        /// <summary>
        /// TripleDES加密，key长度为16
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>TripleDES加密结果</returns>
        public static string EncryptData(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return "";
            }
            TripleDESCryptoServiceProvider Tripledes = new TripleDESCryptoServiceProvider();
            //Tripledes.Mode = CipherMode.ECB;
            //Tripledes.Padding = PaddingMode.PKCS7;
            byte[] b_input = Encoding.UTF8.GetBytes(plainText);
            byte[] b_key = Encoding.UTF8.GetBytes(key);
            MemoryStream tempStream = new MemoryStream();
            //rgbKey即用于对称算法的密钥、rgbIV即用于对称算法的初始化向量，这里均使用b_key
            CryptoStream encStream = new CryptoStream(tempStream, Tripledes.CreateEncryptor(b_key, b_key), CryptoStreamMode.Write);
            encStream.Write(b_input, 0, b_input.Length);
            encStream.Close();
            return Convert.ToBase64String(tempStream.ToArray());
        }

        /// <summary> 
        /// TripleDES解密，key长度为16
        /// </summary>
        /// <param name="input">TripleDES加密的结果</param>
        /// <param name="key">密钥</param>
        /// <returns>TripleDES解密结果</returns>
        public static string DecryptData(string input, string key)
        {
            if (input.IsBase64())
            {
                TripleDESCryptoServiceProvider Tripledes = new TripleDESCryptoServiceProvider();
                byte[] b_input = Convert.FromBase64String(input);
                byte[] b_key = Encoding.UTF8.GetBytes(key);
                MemoryStream tempStream = new MemoryStream();
                //rgbKey即用于对称算法的密钥、rgbIV即用于对称算法的初始化向量，这里均使用b_key
                CryptoStream encStream = new CryptoStream(tempStream, Tripledes.CreateDecryptor(b_key, b_key), CryptoStreamMode.Write);
                encStream.Write(b_input, 0, b_input.Length);
                encStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(tempStream.ToArray());
            }
            else
            {
                return "";
            }
            
        }
    }
}
